package com.itheima.commons.autoconfig.template;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.commons.autoconfig.properties.OssProperties;

import java.io.ByteArrayInputStream;

public class OssTemplate {

    private OssProperties properties;

    public OssTemplate(OssProperties properties) {
        this.properties = properties;
    }

    public String uploadPicture(byte[] imageData, String fileSuffixName) {
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKey(), properties.getSecret());
        // 我们在进行存储文件的时候 不能把所有的文件都存储到同一个目录中
        // 对上传目录进行分离 目录分离算法 根据一个文件名称 --> 自动生成目录层级
        String filePath = getFilePath(fileSuffixName);
        PutObjectResult result = ossClient.putObject(properties.getBucketName(), filePath, new ByteArrayInputStream(imageData));
        //
        // https://hztanhua.oss-cn-hangzhou.aliyuncs.com/images/2021/12/04/06a5a91e2cd941539605b41aacc7d1c6.jpg
        ossClient.shutdown();
        // 返回上传成功后的图片地址
        return properties.getUrl() + filePath;
    }

    public String getFilePath(String fileSuffixName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy") + "/"
                + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/"
                + UUID.fastUUID().toString(true) + "." + fileSuffixName;
    }
}
